<?php
session_start(); 

class Settings extends Controller 
{

	function Intro()
		{
			parent::Controller();	
		}//end method
	
	function index()
		{
			$this->setting();
		}

	function setting()
		{
			$this->load_setting();
			$datas	= $this->common->authenticate();
			global $userId,$now;
			
			if(count($datas)<1)
				{
					$datas	= $this->common->basicvars();
					$data	= $datas;
					$data['siteUrl']		= site_url();
					$data['currentPage']	= base_url();
					$data['center_login']	= true;
					$this->smartyextended->view('user/login',$data);
				}
			else
				{
					$data		= array();
					$data		= $datas;

					$data['count_friends_request']	= $this->common->countFriendRequest($userId);
					$data['count_new_msg']	= $this->common->countNewMsg($userId);
					$data['count_out_request']	= $this->common->countOutRequest($userId);					

					//get user details
					$usrRs		= getRow('users','email,password,firstname, lastname',"user_id='$userId'");
					$usrEmail	= $usrRs['email'];						//get email id
					
					$data['formfirstname'] = $usrRs['firstname'];
					$data['formlastname'] = $usrRs['lastname'];
					
					$data['currentEmail']	=  trim($usrEmail);					//set set login true
					
					/*if(isset($_POST['contact_settings']))				//check contact_email_form submission
						{
							$email		= trim($_POST['new_contact_email_other']);
							
							//validation is done here
							if($email == '')
								$data['error']	= "Please give the new email id !";
							elseif(!isValidEmail($email))
								$data['error']	= "Pleas give the valid email id !";
							else//if simple validation is over
								{
									if(!IsRecordExist4Add('users','user_id',"email='$email' AND user_status='active'"))
									{
									//update lat active field in users table
									if(updateRecords('users',"email='$email'","user_id='$userId'"))
										$data['success']= "Email successfully changed !";
									else
										$data['error']	= "Technical problem !";
									}
									else
										$data['error']	= "Email address already exists.Please enter new email id";
								}
						}//end contact_settings*/
					if(isset($_POST['password_settings']))		//check password_form submission
						{
							$oldPassword	= trim($_POST['old_password']);
							$newPassword	= trim($_POST['new_password']);
							$confPassword	= trim($_POST['confirm_password']);
							
							$usrRs		= getRow('users','show_password',"user_id='$userId'");
							$usrPass	= $usrRs['show_password'];		//get email id
							
							//validation is done here
							if($oldPassword !='' or $newPassword!='')
								{
									if($oldPassword!=$usrPass)
										$data['error']	= "Помилка: Невірно вказаний поточний пароль.";
									elseif(strlen($newPassword)<6)
										$data['error']	= "Помилка: Новий пароль занадто короткий, допустимий від 6 символів. Спробуйте інший.";
									elseif($confPassword =='')
										$data['error']	= "Помилка: Ви не підтвердили новий пароль.";
									elseif($confPassword !=$newPassword)
										$data['error']	= "Помилка: Паролі не співпадають.";
									else//if simple validation is over
										{
											//update password field in users table
											if(updateRecords('users',"show_password='$newPassword', password='".md5($newPassword)."'","user_id='$userId'"))
												$data['success']= "Пароль успішно змінено";
											else
												$data['error']	= "Помилка: Щось пішло не так! Пароль невдалося змінити.";
										}
								}
						}//end password_settings
					elseif(isset($_POST['username_settings']))			//check security_form submission
						{
							$newFirstname		= explode(" ",$_POST['firstname']);
							$newLastname		= explode(" ",$_POST['lastname']);
							
							$data['formfirstname'] = $newFirstname[0];
							$data['formlastname']  = $newLastname[0];
							
							if ($_POST['firstname'] == '')
							{
								$data['error2'] = 'Помилка: Невказане Ім`я.';
							}
							elseif ($_POST['lastname'] == '')
							{
								$data['error2'] = 'Помилка: Невказане прізвище.';
							}
							else
							{
								//update username field in users table
								if(updateRecords('users',"firstname='$newFirstname[0]', lastname='$newLastname[0]'","user_id='$userId'"))
								{
									$data['success2']= "Ім`я успішно змінено";
								}//end update records
								else
								{
									$data['error2']	= "Помилка: Щось пішло не так! Ім`я невдалося змінити.";
								}
							}
						}//end username_settings

					$data['userId']	= $userId;
					$this->smartyextended->view('edit/settings',$data);
				}
			}//end settings()

	function notifications()
		{
			$this->load_setting();
			$datas	= $this->common->authenticate();
			global $userId,$now;
			
			if(count($datas)<1)
				{
					$datas	= $this->common->basicvars();
					$data	= $datas;
					$data['siteUrl']		= site_url();
					$data['currentPage']	= base_url();
					$data['center_login']	= true;
					$this->smartyextended->view('user/login',$data);
				}
			else
				{
					$data		= array();
					$data		= $datas;
					if($_POST['notify_settings_submit'])
						$resultMsg	= $this->_storeNotifySettings($userId);
					$data['notification_content']	= $this->_showNotifySettings($userId);
					$data['show_result']			= true;
					$data['result_msg']				= $resultMsg;
					$data['account_notifications']	= true;
					$this->smartyextended->view('edit/settings',$data);
				}
		}//end join_network()

	function _storeNotifySettings($userId)
		{
			$query	= "SELECT notification_id, notification_name FROM notifications";
			$res	= mysql_query($query);
			if($res)
			while($rs=mysql_fetch_object($res))
				{
					$status		= 0;
					$checkBoxId	= "notify_check_".$rs->notification_id;
					if($_POST[$checkBoxId])
						$status	= 1;
					//echo $_POST[$checkBoxId];
					$isExist	= getTotRec("id","users_status","notification_id=".$rs->notification_id." AND user_id=".$userId);
					if($isExist)
						{
							$up_qry="UPDATE users_status SET notification_status='$status' WHERE user_id='$userId' AND notification_id=".$rs->notification_id;
							if(mysql_query($up_qry))
							$resultMsg	= "Зміни успішно збережено"; 
							else
							$resultMsg	= "Помилка: Зміни невдалося зберегти<br> ".mysql_error();
						}
					else
					{
						$ins_qry="INSERT INTO users_status SET user_id='$userId', notification_id=".$rs->notification_id.", notification_status='$status'";
						if(mysql_query($ins_qry))
						$resultMsg	= "Зміни успішно збережено"; 
						else
						$resultMsg	= "Помилка: Зміни невдалося зберегти<br> ".mysql_error();
						
					}
				}
			return $resultMsg;
		}//end storeFeedSettings()

	function _showNotifySettings($userId)
		{
			global $userId,$now,$mplayer,$mencoder,$rootPath,$adminName,$adminEmail,$siteName,$siteTitle;
			$usrRs			= getRow("users","email","user_id='$userId'");
			$emailContent	=	'<p>Хочете отримувати листи з оповіщеннями на пошту <strong>'.$usrRs[email].'</strong>, коли: </p>';
			$query	= "SELECT notification_id, notification_name FROM notifications";
			$res	= mysql_query($query);
			if($res)
			while($rs=mysql_fetch_object($res))
				{
					$chechBoxId	= "notify_check_".$rs->notification_id;
					$feedRs		= getRow("users_status","notification_status","notification_id=".$rs->notification_id." AND user_id='$userId'");
					$isChecked	= getTotRec("id","users_status","notification_id=".$rs->notification_id." AND user_id='$userId'");
					if($isChecked)
						{
							if($feedRs['notification_status'])
								$checked	= 'checked';
							else 
								$checked	= '';
						}
					else
						$checked = 'checked';
					$content	.= '<p><input type="checkbox" id="'.$chechBoxId.'" name="'.$chechBoxId.'" '.$checked.'>'.$rs->notification_name.'</p>';
				}

			$content	= '<form name="notify_settings_form" method="post" >
							'.$emailContent.$content.'
							<div class="form-submit">
							<input type="hidden" id="notify_settings_submit" name="notify_settings_submit" value="1">
							<input type="submit" class="form-submit round-btn" value="Зберегти">
							</div>
							</form>';
				
			return $content;
		}//end showFeedSettings()

			
	function load_setting()
		{
			global $userId,$now,$adminName,$adminEmail,$siteName,$siteTitle;
			$this->load->model('common');
			
			$userId		= $this->session->userdata('user_id');
			$now		= $this->config->item('now');
			
			$siteVars	= $this->common->getSiteVars();
			$adminName	= $siteVars['adminName'];
			$adminEmail	= $siteVars['adminEmail'];
			$siteName	= $siteVars['siteName'];
			$siteTitle	= $siteVars['siteTitle'];
		}
}
?>